<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第28篇：迭代器和生成器, 张亚飞,飞凡空间,国学,Python,Go">
    <meta name="description" content="学习目标：把可迭代对象、迭代器和生成器的概念和用法掌握
在了解Python的数据结构时，容器(container)、可迭代对象(iterable)、迭代器(iterator)、生成器(generator)、列表/集合/字典推导式(list,">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-w2ezfaoXE0" />
    <title>第28篇：迭代器和生成器 | 飞凡空间</title>
    <link rel="icon" type="image/png" href="/medias/my-logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="飞凡空间" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/my-logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">飞凡空间</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/my-logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">飞凡空间</div>
        <div class="logo-desc">
            
            诚者，天之道也；诚之者，人之道也。诚者，不勉而中，不思而得。从容中道，圣人也；诚之者，择善而固执者也。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/28.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第28篇：迭代器和生成器
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                                <span class="chip bg-color">Python之路</span>
                            </a>
                        
                            <a href="/tags/%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%AF%B9%E8%B1%A1/">
                                <span class="chip bg-color">可迭代对象</span>
                            </a>
                        
                            <a href="/tags/%E8%BF%AD%E4%BB%A3%E5%99%A8/">
                                <span class="chip bg-color">迭代器</span>
                            </a>
                        
                            <a href="/tags/%E7%94%9F%E6%88%90%E5%99%A8/">
                                <span class="chip bg-color">生成器</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Python/" class="post-category">
                                Python
                            </a>
                        
                            <a href="/categories/Python/base/" class="post-category">
                                base
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-12-27
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    29 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>学习目标</strong>：把可迭代对象、迭代器和生成器的概念和用法掌握</p>
<p>在了解Python的数据结构时，容器(container)、可迭代对象(iterable)、迭代器(iterator)、生成器(generator)、列表/集合/字典推导式(list,set,dict comprehension)众多概念参杂在一起，难免让初学者一头雾水，我将用一篇文章试图将这些概念以及它们之间的关系捋清楚。</p>
<p>它们之间的关系可以用下图表示：</p>
<p><img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/20201203210913375.png" alt="关系图"></p>
<p>这张图解释了他们之间的从属关系和转换关系</p>
<p><img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/20201203210845234.png" alt="关系图2"></p>
<ul>
<li>可迭代对象：其中实现了<code>__iter__</code>方法的对象就叫做可迭代对象。（ 严格来说，可迭代对象是任何实现了 <strong><code>iter()</code></strong> 方法或者实现了序列（Sequence）语义中的 **<code>getitem()</code> **方法的任意自定义类对象。）</li>
<li>迭代器：既实现了<code>__iter__</code>，也实现了<code>__next__</code>方法的对象叫做迭代器；</li>
<li>生成器：有两种，一种是具有yield关键字的函数都是生成器，其二是生成器表达式，隐式的实现了迭代器协议。</li>
</ul>
<h3 id="一、容器"><a href="#一、容器" class="headerlink" title="一、容器"></a>一、容器</h3><p>容器是一种把多个元素组织在一起的数据结构，容器中的元素可以逐个地迭代获取，可以用<code>in</code>, <code>not in</code>关键字判断元素是否包含在容器中。通常这类数据结构把所有的元素存储在内存中。在Python中，常见的容器对象有：</p>
<ul>
<li><code>list</code>, <code>deque</code>, ….</li>
<li><code>set</code>, <code>frozensets</code>, ….</li>
<li><code>dict</code>, <code>defaultdict</code>, <code>OrderedDict</code>,<code>Counter</code>, ….</li>
<li><code>tuple</code>, <code>namedtuple</code>, …</li>
<li><code>str</code></li>
</ul>
<p>容器比较容易理解，因为你就可以把它看作是一个盒子、一栋房子、一个柜子，里面可以塞任何东西。从技术角度来说，当它可以用来询问某个元素是否包含在其中时，那么这个对象就可以认为是一个容器，比如 list，set，tuples都是容器对象：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">1</span> <span class="token keyword">in</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span>      <span class="token comment" spellcheck="true"># lists</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">4</span> <span class="token operator">not</span> <span class="token keyword">in</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">1</span> <span class="token keyword">in</span> <span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">}</span>      <span class="token comment" spellcheck="true"># sets</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">4</span> <span class="token operator">not</span> <span class="token keyword">in</span> <span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">}</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">1</span> <span class="token keyword">in</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span>      <span class="token comment" spellcheck="true"># tuples</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">4</span> <span class="token operator">not</span> <span class="token keyword">in</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>询问某元素是否在<code>dict</code>中用<code>dict</code>的中key：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> d <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">:</span> <span class="token string">'foo'</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">:</span> <span class="token string">'bar'</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">:</span> <span class="token string">'qux'</span><span class="token punctuation">}</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token number">1</span> <span class="token keyword">in</span> d
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token string">'foo'</span> <span class="token operator">not</span> <span class="token keyword">in</span> d  <span class="token comment" spellcheck="true"># 'foo' 不是dict中的元素</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>询问某substring是否在string中：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> s <span class="token operator">=</span> <span class="token string">'foobar'</span>
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token string">'b'</span> <span class="token keyword">in</span> s
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token string">'x'</span> <span class="token operator">not</span> <span class="token keyword">in</span> s
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">assert</span> <span class="token string">'foo'</span> <span class="token keyword">in</span> s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>尽管绝大多数容器都提供了某种方式来获取其中的每一个元素，但这并不是容器本身提供的能力，而是<strong>可迭代对象</strong>赋予了容器这种能力。</p>
<p><strong>容器的两个特点</strong></p>
<ol>
<li>容器中的元素可通过迭代获取。</li>
<li>所有容器中的元素被存储在内存中。(不同于其它迭代器得地方)</li>
</ol>
<h3 id="二、迭代器协议"><a href="#二、迭代器协议" class="headerlink" title="二、迭代器协议"></a>二、迭代器协议</h3><p>在讨论可迭代对象、迭代器和生成器之前，先说明一下<strong>迭代器模式（iterator pattern）</strong>，维基百科这么解释：</p>
<blockquote>
<p>迭代器是一种最简单也最常见的设计模式。它可以让用户透过特定的接口巡访容器中的每一个元素而不用了解底层的实现。</p>
</blockquote>
<p>迭代是数据处理的基石。当内存中放不下数据集时，我们要找到一种<strong>惰性</strong>获取数据的方式，即按需一次获取一个数据项，这就是迭代器模式。</p>
<p><strong>序列可迭代的原因：iter函数</strong><br>我们都知道序列是可迭代的。当解释器需要迭代对象x时，会自动调用iter(x)<strong>。</strong><br>内置的iter函数有以下作用：</p>
<ul>
<li>检查对象是否实现了<code>__iter__</code>方法，如果实现了就调用它，获得一个迭代器。</li>
<li>如果没有实现<code>__iter__</code>方法，但是实现了<code>__getitem__</code>方法，python会创建一个迭代器，尝试按顺序（从索引0开始）获取元素。</li>
<li>如果尝试失败，python会抛出<code>TypeError</code>异常，通常会提示”C object is not iterable”，其中C是目标对象所属的类。</li>
</ul>
<p>截止到Python3.6，基本上所有的Python序列也都实现了<code>__getitem__</code>方法，这是保证任何序列都可迭代的原因。当然标准的序列也都实现了<code>__iter__</code>方法，之所以对<code>__getitem__</code>也可以创建迭代器是为了向后兼容，未来可能不在这么做。</p>
<p>但是，从Python3.4开始，检查x能否迭代，最准确的方法是调用iter(x)函数，如果不可迭代，再处理TypeError异常。</p>
<h3 id="三、可迭代对象"><a href="#三、可迭代对象" class="headerlink" title="三、可迭代对象"></a>三、可迭代对象</h3><p>严格来说，可迭代对象是任何实现了<code>__iter__()</code> 方法或者实现了序列（Sequence）语义中的<code>__getitem__() </code>方法的任意自定义类对象。以通俗简单的方式来讲，可迭代对象就是能够逐一返回其成员项的对象，其可用于 for 循环。通过使用<code>iter()</code>方法，我们能将可迭代对象返回成迭代器。例如：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">from</span> collections <span class="token keyword">import</span> Iterable
<span class="token comment" spellcheck="true"># 定义一个列表，其本身是可迭代对象</span>
list_a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'a'</span><span class="token punctuation">,</span> <span class="token string">'b'</span><span class="token punctuation">,</span> <span class="token string">'c'</span><span class="token punctuation">]</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>isinstance<span class="token punctuation">(</span>list_a<span class="token punctuation">,</span> Iterable<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># True</span>
new_a <span class="token operator">=</span> iter<span class="token punctuation">(</span>list_a<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="1-实现可迭代对象的两种方式"><a href="#1-实现可迭代对象的两种方式" class="headerlink" title="1. 实现可迭代对象的两种方式"></a>1. 实现可迭代对象的两种方式</h4><p>那么下面我们分别来讨论下这两种实现方案。</p>
<ol>
<li>实现<code>__iter__</code><br>这种方式是你必须为你的类实现<strong>iter</strong>()方法，该方法返回的必须是一个迭代器对象，下面会讲到。<br>注意：可迭代对象得__iter__方法，返回的必须是迭代器，但不一定是self<br>（这与迭代器的__iter__不同，因为迭代器的self一定是迭代器，而可迭代对象的self不一定是迭代器）</li>
</ol>
<blockquote>
<p><code>__iter__</code>方法说明<br>该方法返回的是当前对象的迭代器类的实例。因为可迭代对象与迭代器都要实现这个方法，因此有以下两种写法。<br>写法一：用于可迭代对象类的写法，返回该可迭代对象的迭代器类的实例。<br>写法二：用于迭代器类的写法，直接返回self（即自己本身），表示自身即是自己的迭代器。</p>
</blockquote>
<p>例如：<code>pytorch</code>的<code>Dataloader</code>类，其<code>__iter__</code>方法如下：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">__iter__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">if</span> self<span class="token punctuation">.</span>num_workers <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> _SingleProcessDataLoaderIter<span class="token punctuation">(</span>self<span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> _MultiProcessingDataLoaderIter<span class="token punctuation">(</span>self<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>实现<strong>getitem</strong><br>序列：序列(Sequence)的迭代通过实现<strong>getitem</strong>() 方法来使用整数索引进行高效的元素访问。同时，你必须为其定义一个返回序列长度的<strong>len</strong>() 方法。例如上面例子中的 list, str, tuple, bytes。序列数据结构的存储是一段连续的内存空间，其直接使用整数索引进行寻址，查找元素非常高效，但是插入删除元素时效率低下。<br>字典：有的童鞋会说，dict 也实现了<strong>getitem</strong> 和<strong>len</strong> 协议，为何dict 不属于序列？原因是它并不是通过整数索引来顺序迭代，而是通过任意的不可变键(immutable key) 来进行逐个查找的。所以 dict 的迭代还是因为其实现了__iter__。</li>
</ol>
<h4 id="2-工作方式-转换为迭代器的方式"><a href="#2-工作方式-转换为迭代器的方式" class="headerlink" title="2. 工作方式(转换为迭代器的方式)"></a>2. 工作方式(转换为迭代器的方式)</h4><ul>
<li>第一种工作方式：当把一个可迭代对象 x 作为参数传给内置函数 iter() 时，它会返回该对象的迭代器以供迭代。</li>
<li>第二种工作方式：但通常我们并不需要通过iter()函数，而是直接使用 for 对可迭代对象进行遍历，for 语句会为你自动处理那些操作：<br>(1)如果实现了__iter__，则自动调用 iter(x) 来获取迭代器。<br>(2) 如果实现了 <strong>getitem</strong> 和 <strong>len</strong> 协议，其会自动创建一个迭代器，并尝试从索引 0 开始获取元素，若尝试失败，会引发一个 TypeError。</li>
</ul>
<h4 id="3-类型判断"><a href="#3-类型判断" class="headerlink" title="3. 类型判断"></a>3. 类型判断</h4><p>判断一个对象是否是一个可迭代对象，可以使用 collections.abc.Iterable。</p>
<pre class="line-numbers language-python"><code class="language-python">In <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token keyword">from</span> collections<span class="token punctuation">.</span>abc <span class="token keyword">import</span> Iterable
In <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">:</span> isinstance<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">,</span> Iterable<span class="token punctuation">)</span>
Out<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token boolean">True</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h3 id="四、迭代器"><a href="#四、迭代器" class="headerlink" title="四、迭代器"></a>四、迭代器</h3><p>即实现了迭代器协议的对象就是一个迭代器，迭代器协议由 <strong>iter</strong>() 和 <strong>next</strong>() 共同组成。</p>
<ul>
<li><code>__iter__</code>必须返回迭代器对象本身。</li>
<li><em><em>next</em></em> 应从容器中返回下一项，如果已经没有数据项可返回时，则需引发 <code>StopIteration</code> 异常，继续调用其<code>__next__</code>应再次引发 <code>StopIteration</code>异常。</li>
</ul>
<h4 id="1-迭代器的实现-iter-与-next-方法说明"><a href="#1-迭代器的实现-iter-与-next-方法说明" class="headerlink" title="1. 迭代器的实现(__iter__与__next__方法说明)"></a>1. 迭代器的实现(<code>__iter__</code>与<code>__next__</code>方法说明)</h4><p>一个迭代器应有的样子应该是这样的：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">Iterator</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__iter__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">return</span> self
    <span class="token keyword">def</span> <span class="token function">__next__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">pass</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p><code>__iter__</code>与<code>__next__</code>方法说明<br>1）<code>__iter__</code><br>该方法返回的是当前对象的迭代器类的实例。因为可迭代对象与迭代器都要实现这个方法，因此有以下两种写法。<br>写法一：用于可迭代对象类的写法，返回该可迭代对象的迭代器类的实例。<br>写法二：用于迭代器类的写法，直接返回self（即自己本身），表示自身即是自己的迭代器。<br>2）<code>__next__</code><br>返回迭代的下一步，实现该方法时注意最后超出边界要抛出StopIteration异常。</p>
</blockquote>
<h4 id="2-迭代器的特点"><a href="#2-迭代器的特点" class="headerlink" title="2. 迭代器的特点"></a>2. 迭代器的特点</h4><ul>
<li>迭代器是一个带状态的对象，迭代器内部持有一个状态，该状态用于记录当前迭代所在位置，以便于下次迭代的时候获取正确的元素。迭代器可以通过next()方法来迭代获取下一个值。</li>
<li>迭代器不会一次性吧所有元素都加载到内存，而是需要的时候才返回结果。</li>
</ul>
<h4 id="3-工作方式"><a href="#3-工作方式" class="headerlink" title="3. 工作方式"></a>3. 工作方式</h4><p>迭代器用来表示一连串数据流的对象，当 for 语句自动返回可迭代对象的迭代器时，for 将重复调用其 <strong>next</strong>() 方法将逐个返回流中的项，直到迭代器引发 StopIteration 异常后终止循环。此时该迭代器数据项已耗尽，不能再使用。</p>
<h3 id="五、可迭代对象和迭代器关系"><a href="#五、可迭代对象和迭代器关系" class="headerlink" title="五、可迭代对象和迭代器关系"></a>五、可迭代对象和迭代器关系</h3><p><strong>使用iter内置函数可以获取迭代器对象。</strong>也就是说，如果一个对象实现了能返回迭代器的<code>__iter__</code>方法，那么对象就是可迭代的，序列都可以迭代；实现了<code>__getitem__</code>方法，而且其参数是从零开始的索引，这种对象也是可迭代的。</p>
<p>因此可以明确<strong>可迭代对象</strong>和<strong>迭代器</strong>之间的关系：<strong>Python从可迭代的对象中获取迭代器。</strong></p>
<p>标准的迭代器接口有两个方法，即：</p>
<ul>
<li><code>__next__</code>:返回下一个可用元素，如果没有元素，抛出<code>StopIteration</code>异常</li>
<li><code>__iter__</code>:返回self，以便在应该使用可迭代对象的地方使用迭代器，比如for循环中。</li>
</ul>
<p>因为迭代器只需<code>__next__</code>和<code>__iter__</code>两个方法，所以除了调用next()方法，以及捕获<code>StopIteration</code>异常之外，没有办法检查是否还有遗留的元素。此外，也没有办法还原迭代器。如果想再次迭代，那就要调用<code>iter(…)</code>，传入之前构建迭代器的可迭代对象。</p>
<p>构建<code>可迭代对象</code>和<code>迭代器</code>时经常会出现错误，原因是混淆了两者。要知道，<code>可迭代的对象</code>有个<code>__iter__</code>方法，*<strong>调用该方法每次都实例化一个新的迭代器*</strong>；而<code>迭代器</code>要实现<code>__next__</code>方法，返回单个元素，此外还要实现<code>__iter__</code>方法，返回迭代器本身(self)，如图。因此，<strong>迭代器可以迭代，但是可迭代的对象不是迭代器</strong>。</p>
<p><img src="https://pic2.zhimg.com/80/v2-e519a06b7c4a7db2d3b854dffd9cfd69_720w.jpg" alt="img"></p>
<p><strong>需要注意的是：</strong></p>
<p>可迭代的对象必须实现<code>__iter__</code>方法，但*<strong>不能*</strong>实现<code>__next__</code>方法。另一方面，迭代器应该一直可以迭代，迭代器的<code>__iter__</code>方法应该返回自身。虽然可迭代对象和迭代器都有<code>__iter__</code>方法，但是两者的功能不一样，再次强调一下，可迭代对象的<code>__iter__</code>用于实例化一个迭代器对象，而迭代器中的<code>__iter__</code>用于返回迭代器本身，与<code>__next__</code>共同完成迭代器的迭代作用。</p>
<h3 id="六、生成器"><a href="#六、生成器" class="headerlink" title="六、生成器"></a>六、生成器</h3><p><strong>生成器是一种特殊的迭代器，生成器自动实现了“迭代器协议”（即<code>__iter__</code>和<code>__next__</code>方法），不需要再手动实现两方法</strong>。在Python中创建迭代器最方便的方法是使用生成器。生成器也是迭代器。生成器的语法类似于函数，但是不返回值。为了显示序列中的每一个元素，会使用yield语句。只要Python函数的定义体中有yield关键字，该函数就是生成器函数。调用生成器函数时，会返回一个生成器对象。获取生成器通常有两种方式：<strong>生成器函数</strong>和<strong>生成器表达式</strong>。</p>
<h4 id="1-生成器主要的特点"><a href="#1-生成器主要的特点" class="headerlink" title="1. 生成器主要的特点"></a>1. 生成器主要的特点</h4><p>1、生成器通过关键字yield自动实现了“迭代器协议”（即<code>__iter__</code>和<code>__next__</code>方法），不需要再手动实现两方法。生成器特殊的地方在于函数体中没有return关键字，函数的返回值是一个生成器对象。当执行f=fab()返回的是一个生成器对象，此时函数体中的代码并不会执行，只有显示或隐示地调用next的时候才会真正执行里面的代码。</p>
<p>2、生成器可以传入数据进行计算(而修改普通迭代器的当前迭代值往往会发生异常)，并根据变量内容计算结果后返回。</p>
<p>3、迭代器不会一次把所有的元素加载到内存，而是调用的时候才生成返回结果(这点相同于迭代器)</p>
<p>4、可以通过for循环进行迭代(因为生成器是迭代器)</p>
<h4 id="2-实现生成器"><a href="#2-实现生成器" class="headerlink" title="2. 实现生成器"></a>2. 实现生成器</h4><h5 id="方式1：生成器函数"><a href="#方式1：生成器函数" class="headerlink" title="方式1：生成器函数"></a>方式1：生成器函数</h5><p>和普通函数的 return 返回不同，生成器函数使用 yield。yield可以理解为return，返回后面的值给调用者。不同的是return返回后，函数会释放，而生成器则不会。在直接调用next方法或用for语句进行下一次迭代时，生成器会从yield下一句开始执行，直至遇到下一个yield。生成器特殊的地方在于函数体中没有return关键字，函数的返回值是一个生成器对象。当执行f=fab()返回的是一个生成器对象，此时函数体中的代码并不会执行，只有显示或隐示地调用next的时候才会真正执行里面的代码。</p>
<p>首先，如果你还没有对yield有个初步分认识，那么你先把yield看做“return”，这个是直观的，它首先是个return，普通的return是什么意思，就是在程序中返回某个值，返回之后程序就不再往下运行了。看做return之后再把它看做一个是生成器（generator）的一部分（带yield的函数才是真正的迭代器），好了，如果你对这些不明白的话，那先把yield看做return,然后直接看下面的程序，你就会明白yield的全部意思了：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">foo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"starting..."</span><span class="token punctuation">)</span>
    <span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
        res <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token number">4</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"res:"</span><span class="token punctuation">,</span>res<span class="token punctuation">)</span>
g <span class="token operator">=</span> foo<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"*"</span><span class="token operator">*</span><span class="token number">20</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token triple-quoted-string string">"""
starting...
4
********************
res: None
4
"""</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>我直接解释代码运行顺序，相当于代码单步调试：</strong></p>
<ul>
<li>1.程序开始执行以后，因为foo函数中有yield关键字，所以foo函数并不会真的执行，而是先得到一个生成器g(相当于一个对象)</li>
<li>2.直到调用next方法，foo函数正式开始执行，先执行foo函数中的print方法，然后进入while循环</li>
<li>3.程序遇到yield关键字，然后把yield想想成return,return了一个4之后，程序停止，<span style="color: red"> 并没有执行赋值给res操作</span>，此时next(g)语句执行完成，所以输出的前两行（第一个是while上面的print的结果,第二个是return出的结果）是执行print(next(g))的结果，</li>
<li>4.程序执行print(“*”<em>20)，输出20个</em></li>
<li>5.又开始执行下面的print(next(g)),这个时候和上面那个差不多，不过不同的是，这个时候是从刚才那个<span style="color:red">next程序停止的地方开始执行的</span>，也就是要执行res的赋值操作，<span style="color:blue">这时候要注意，这个时候赋值操作的右边是没有值的（因为刚才那个是return出去了，并没有给赋值操作的左边传参数）</span>，所以这个时候res赋值是None,所以接着下面的输出就是res:None,</li>
<li>6.程序会继续在while里执行，又一次碰到yield,这个时候同样return 出4，然后程序停止，print函数输出的4就是这次return出的4.</li>
</ul>
<p><strong>到这里你可能就明白yield和return的关系和区别了，带yield的函数是一个生成器，而不是一个函数了，这个生成器有一个函数就是next函数，next就相当于“下一步”生成哪个数，这一次的next开始的地方是接着上一次的next停止的地方执行的，所以调用next的时候，生成器并不会从foo函数的开始执行，只是接着上一步停止的地方开始，然后遇到yield后，return出要生成的数，此步就结束。</strong></p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">foo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"starting..."</span><span class="token punctuation">)</span>
    <span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
        res <span class="token operator">=</span> <span class="token keyword">yield</span> <span class="token number">4</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"res:"</span><span class="token punctuation">,</span>res<span class="token punctuation">)</span>
g <span class="token operator">=</span> foo<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"*"</span><span class="token operator">*</span><span class="token number">20</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>g<span class="token punctuation">.</span>send<span class="token punctuation">(</span><span class="token number">7</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>再看一个这个生成器的send函数的例子，这个例子就把上面那个例子的最后一行换掉了，输出结果：</p>
<pre class="line-numbers language-python"><code class="language-python">starting<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token number">4</span>
<span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span><span class="token operator">**</span>
res<span class="token punctuation">:</span> <span class="token number">7</span>
<span class="token number">4</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>先大致说一下send函数的概念：此时你应该注意到上面那个的蓝色字体，还有上面那个res的值为什么是None，这个变成了7，到底为什么，这是因为，send是发送一个参数给res的，因为上面讲到，return的时候，并没有把4赋值给res，下次执行的时候只好继续执行赋值操作，只好赋值为None了，而如果用send的话，开始执行的时候，先接着上一次（return 4之后）执行，先把7赋值给了res,然后执行next的作用，遇见下一回的yield，return出结果后结束。</p>
<p> 关键点：</p>
<ul>
<li>程序执行g.send(7)，程序会从yield关键字那一行继续向下运行，send会把7这个值赋值给res变量</li>
<li>由于send方法中包含next()方法，所以程序会继续向下运行执行print方法，然后再次进入while循环</li>
<li>程序执行再次遇到yield关键字，yield会返回后面的值后，程序再次暂停，直到再次调用next方法或send方法。</li>
</ul>
<p>下面再看几个例子：</p>
<ul>
<li><p>示例1</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">gen_123</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>  <span class="token comment" spellcheck="true"># 只要Python代码中包含yield，该函数就是生成器函数</span>
    <span class="token keyword">yield</span> <span class="token number">1</span>    <span class="token comment" spellcheck="true">#生成器函数的定义体中通常都有循环，不过这不是必要条件；此处重复使用了3次yield</span>
    <span class="token keyword">yield</span> <span class="token number">2</span>
    <span class="token keyword">yield</span> <span class="token number">3</span>

<span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">'__main__'</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>gen_123<span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 可以看出gen_123是函数对象</span>
    <span class="token comment" spellcheck="true"># &lt;function gen_123 at 0x10be19></span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>gen_123<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 函数调用时返回的是一个生成器对象</span>
    <span class="token comment" spellcheck="true"># &lt;generator object gen_123 at 0x10be31></span>

    <span class="token keyword">for</span> i <span class="token keyword">in</span> gen_123<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token comment" spellcheck="true"># 生成器是迭代器，会生成传给yield关键字的表达式的值</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>    
        <span class="token comment" spellcheck="true"># 1</span>
        <span class="token comment" spellcheck="true"># 2</span>
        <span class="token comment" spellcheck="true"># 3</span>
    g <span class="token operator">=</span> gen_123<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 为了仔细检查，把生成器对象赋值给g</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 1</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 2</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 3</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 生成器函数的定义体执行完毕后，生成器对象会抛出异常。</span>
<span class="token comment" spellcheck="true"># Traceback (most recent call last):</span>
<span class="token comment" spellcheck="true">#   File "test.py", line 17, in &lt;module></span>
<span class="token comment" spellcheck="true">#     print(next(g))</span>
<span class="token comment" spellcheck="true"># StopIteration</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>只要Python代码中包含yield，该函数就是生成器函数</p>
<ul>
<li>生成器函数的定义体中通常都有循环，不过这不是必要条件；此处重复使用了3次yield</li>
<li>可以看出gen_123是函数对象</li>
<li>函数调用时返回的是一个生成器对象</li>
<li>生成器是迭代器，会<code>生成</code>传给yield关键字的表达式的值</li>
<li>为了仔细检查，把生成器对象赋值给g</li>
<li>因为g是迭代器，所以调用next(g)会获取yield<code>生成</code>的下一个元素</li>
<li>生成器函数的定义体执行完毕后，生成器对象会抛出异常。</li>
</ul>
</li>
<li><p>示例2</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 1. 定义生成器</span>
<span class="token keyword">def</span> <span class="token function">myList</span><span class="token punctuation">(</span>num<span class="token punctuation">)</span><span class="token punctuation">:</span>
    now <span class="token operator">=</span> <span class="token number">0</span>           <span class="token comment" spellcheck="true"># 当前迭代值，初始为0</span>
    <span class="token keyword">while</span> now <span class="token operator">&lt;</span> num<span class="token punctuation">:</span>
        val <span class="token operator">=</span> <span class="token keyword">yield</span> now                      <span class="token comment" spellcheck="true"># 返回当前迭代值，并接受可能的send发送值；</span>
        now <span class="token operator">=</span> now <span class="token operator">+</span> <span class="token number">1</span> <span class="token keyword">if</span> val <span class="token keyword">is</span> None <span class="token keyword">else</span> val  <span class="token comment" spellcheck="true"># val为None，迭代值自增1，否则重新设定当前迭代值为val</span>

<span class="token comment" spellcheck="true"># 2. 测试代码</span>
my_list <span class="token operator">=</span> myList<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span>   <span class="token comment" spellcheck="true"># 得到一个生成器对象</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>my_list<span class="token punctuation">.</span>__next__<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 返回当前迭代值</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>my_list<span class="token punctuation">.</span>__next__<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>my_list<span class="token punctuation">.</span>send<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 重新设定当前的迭代值</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'next'</span><span class="token punctuation">,</span> next<span class="token punctuation">(</span>my_list<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>dir<span class="token punctuation">(</span>my_list<span class="token punctuation">)</span><span class="token punctuation">)</span>    <span class="token comment" spellcheck="true"># 返回该对象所拥有的方法名，可以看到__iter__与next在其中</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python"><span class="token triple-quoted-string string">"""
0
1
3
4
['__class__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__next__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']
"""</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>generator其实有第2种调用方法(恢复执行)，即通过send(value)方法将value作为yield表达式的当前值，你可以用该值再对其他变量进行赋值，这一段代码就很好理解了。当我们调用send(value)方法时，generator正由于yield的缘故被暂停了。此时，send(value)方法传入的值作为yield表达式的值，函数中又将该值赋给了变量s，然后print函数打印s，循环再遇到yield，暂停返回。</p>
</li>
<li><p>示例3</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">odd_func</span><span class="token punctuation">(</span>start<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">,</span> end<span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> val <span class="token keyword">in</span> range<span class="token punctuation">(</span>start<span class="token punctuation">,</span> end <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> val <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">1</span><span class="token punctuation">:</span>
            <span class="token keyword">yield</span> val

of <span class="token operator">=</span> odd_func<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>of<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># &lt;generator object odd_func at 0x00000132300C85C8></span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>of<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 1</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>of<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 3</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>of<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 5</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>of<span class="token punctuation">)</span><span class="token punctuation">)</span> 
<span class="token triple-quoted-string string">"""
Traceback (most recent call last):
  File "D:/python/Python之路/6 生成器迭代器生成式/code/example2.py", line 21, in &lt;module>
    print(next(of))
StopIteration
"""</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>示例4</p>
<p><code>yeild</code>后面不跟任何值，这时<code>yeild</code>返回的值只能通过send（）送进去。但此时首先要调用一次send(None)或者next()方法.</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">gen</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
        s <span class="token operator">=</span> <span class="token keyword">yield</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span>

g <span class="token operator">=</span> gen<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># g.send('hello')  # 这里很重要，向一个刚开始的生成器直接send一个值，会报错，所以我们得先调用next方法</span>
<span class="token comment" spellcheck="true"># Traceback (most recent call last):</span>
<span class="token comment" spellcheck="true">#   File "D:/python/Python之路/6 生成器迭代器生成式/code/example3.py", line 16, in &lt;module></span>
<span class="token comment" spellcheck="true">#     g.send('hello')</span>
<span class="token comment" spellcheck="true"># TypeError: can't send non-None value to a just-started generator</span>
<span class="token comment" spellcheck="true"># 让生成器向后移动一个位置后再send值</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>g<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 或者调用send(None)</span>
g<span class="token punctuation">.</span>send<span class="token punctuation">(</span><span class="token string">'hello'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>TypeError: can’t send non-None value to a just-started generator </code>告诉我们，刚开始的生成器只能send(None)。调用send(value)时要注意，要确保，generator是在yield处被暂停了，如此才能向yield表达式传值，否则将会报错(如上所示)，可通过next()方法或send(None)使generator执行到yield。</p>
</li>
</ul>
<h5 id="方式2：生成器表达式-generator-expression"><a href="#方式2：生成器表达式-generator-expression" class="headerlink" title="方式2：生成器表达式(generator expression)"></a>方式2：生成器表达式(generator expression)</h5><p>生成器表达式是列表推倒式的生成器版本，看起来像列表推导式，但是它返回的是一个生成器对象而不是列表对象。</p>
<pre class="line-numbers language-python"><code class="language-python">a <span class="token operator">=</span> <span class="token punctuation">(</span>x <span class="token keyword">for</span> x <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># &lt;generator object &lt;genexpr> at 0x000001DB6DD91748></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>简单的生成器函数，可以替换成生成器表达式。生成器表达式可以理解为列表推导的惰性版本：不会迫切的构建列表，而是返回一个生成器，按需惰性生成元素。也就是说，如果列表推导是制造工厂的列表，那么生成器表达式就是制造生成器的工厂。如下演示了一个简单的生成器表达式，并且与列表推导做了对比。</p>
<pre class="line-numbers language-python"><code class="language-python">In <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token keyword">def</span> <span class="token function">gen_AB</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>            <span class="token comment" spellcheck="true"># 1</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'start'</span><span class="token punctuation">)</span>       
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">yield</span> <span class="token string">'A'</span>            
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'continue'</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">yield</span> <span class="token string">'B'</span>            
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'end.'</span><span class="token punctuation">)</span>        
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>

In <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">:</span> res1 <span class="token operator">=</span> <span class="token punctuation">[</span>x<span class="token operator">*</span><span class="token number">3</span> <span class="token keyword">for</span> x <span class="token keyword">in</span> gen_AB<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span>  <span class="token comment" spellcheck="true"># 2</span>
start
<span class="token keyword">continue</span>
end<span class="token punctuation">.</span>

In <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token keyword">for</span> i <span class="token keyword">in</span> res1<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>       <span class="token comment" spellcheck="true"># 3</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'-->'</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>      
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>
AAA
BBB

In <span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span><span class="token punctuation">:</span> res2 <span class="token operator">=</span> <span class="token punctuation">(</span>x<span class="token operator">*</span><span class="token number">3</span> <span class="token keyword">for</span> x <span class="token keyword">in</span> gen_AB<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 4</span>

In <span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">:</span> res2  <span class="token comment" spellcheck="true"># 5</span>
<span class="token operator">&lt;</span>generator object <span class="token operator">&lt;</span>genexpr<span class="token operator">></span> at <span class="token number">0x106a07620</span><span class="token operator">></span>

In <span class="token punctuation">[</span><span class="token number">6</span><span class="token punctuation">]</span><span class="token punctuation">:</span> <span class="token keyword">for</span> i <span class="token keyword">in</span> res2<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>       <span class="token comment" spellcheck="true"># 6</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>     <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'-->'</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>
start   
<span class="token operator">-</span><span class="token operator">-</span><span class="token operator">></span> A   
<span class="token keyword">continue</span>
<span class="token operator">-</span><span class="token operator">-</span><span class="token operator">></span> B       
end<span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>创建gen_AB函数</li>
<li>列表推到迫切的迭代gen_AB()函数生成的生成器对象产出的元素：’A’和’B’。注意。下面输出的是start、continue、end.。</li>
<li>for循环迭代列表推导生成的res1列表</li>
<li>把生成器表达式返回的值赋值给res2。只需调用gen_AB()函数，虽然调用时会返回一个生成器，但是这里并不使用。</li>
<li>可以看出res2是一个生成器对象。</li>
<li>只有for循环迭代res2时，gen_AB函数的定义体才会真正执行。for循环每次迭代时会隐式调用next(res2)，前进到gen_AB函数中的下一个yield语句。注意，gen_AB函数的输出与for循环中print函数的输出夹杂在一起。</li>
</ul>
<p>生成器表达式是创建生成器的简洁句法，这样无需定义函数再调用。不过，生成器函数灵活的多，可以使用多个语句实现复杂的逻辑，也可以作为<code>协程</code>(后面有机会讲到)使用。遇到简单的情况时，可以使用生成器表达式，因为这样扫一眼就知道代码的作用。其实选择那种句法很容易判断：如果生成器表达式需要分行写，倾向于定义成生成器函数，以便提高可读性；此外生成器函数有名称，因此可以重用。</p>
<pre class="line-numbers language-python"><code class="language-python">a <span class="token operator">=</span> <span class="token punctuation">(</span>i <span class="token keyword">for</span> i <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token string">'__next__'</span> <span class="token keyword">in</span> dir<span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># True</span>
<span class="token string">'__iter__'</span> <span class="token keyword">in</span> dir<span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># True</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p><strong>以上可以看出，生成器也是一种迭代器！</strong></p>
<p>前面我们提到了惰性计算。其实，我们有时候使用生成器而不是传统的函数时，正是因为惰性计算有好处—只计算需要的数据，并且整个系列不需要一次性全部驻留在内存中。事实上，生成器完全可以有效的生产数值的无限序列，举一个例子，斐波那契数列是一个经典的无限数字序列，下面用生成器可以产生这个无穷级数：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">fibonacci</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    a <span class="token operator">=</span> <span class="token number">0</span>
    b <span class="token operator">=</span> <span class="token number">1</span>
    <span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
        <span class="token keyword">yield</span> a
        future <span class="token operator">=</span> a <span class="token operator">+</span> b
        a <span class="token operator">=</span> b
        b <span class="token operator">=</span> future


<span class="token keyword">if</span> __name__ <span class="token operator">==</span> <span class="token string">'__main__'</span><span class="token punctuation">:</span>
    fib <span class="token operator">=</span> fibonacci<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> _ <span class="token keyword">in</span> range<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>next<span class="token punctuation">(</span>fib<span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="七、标准库中的生成器函数"><a href="#七、标准库中的生成器函数" class="headerlink" title="七、标准库中的生成器函数"></a>七、标准库中的生成器函数</h3><h4 id="1-用于过滤的生成器函数"><a href="#1-用于过滤的生成器函数" class="headerlink" title="1. 用于过滤的生成器函数"></a>1. 用于过滤的生成器函数</h4><table>
<thead>
<tr>
<th>模块</th>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>itertools</td>
<td>compress(it, selector_it)</td>
<td>并行处理两个可迭代的对象；如果 selector_it 中的元素是真值，产出 it 中对应的元素</td>
</tr>
<tr>
<td>itertools</td>
<td>dropwhile(predicate, it)</td>
<td>处理 it，跳过 predicate 的计算结果为真值的元 素，然后产出剩下的各个元素（不再进一步检 查）</td>
</tr>
<tr>
<td></td>
<td>filter(predicate, it)</td>
<td>把 it 中的各个元素传给 predicate，如果 predicate(item) 返回真值，那么产出对应的元 素；如果 predicate 是 None，那么只产出真值元 素</td>
</tr>
<tr>
<td>itertools</td>
<td>filterfalse(predicate, it)</td>
<td>与 filter 函数的作用类似，不过 predicate 的 逻辑是相反的：predicate 返回假值时产出对应 的元素</td>
</tr>
<tr>
<td>itertools</td>
<td>islice(it, stop) 或 islice(it, start, stop, step=1)</td>
<td>产出 it 的切片，作用类似于 s[:stop] 或 s[start:stop:step]，不过 it 可以是任何可迭代 的对象，而且这个函数实现的是惰性操作</td>
</tr>
<tr>
<td>itertools</td>
<td>takewhile(predicate, it)</td>
<td>predicate 返回真值时产出对应的元素，然后立 即停止，不再继续检查</td>
</tr>
</tbody></table>
<h4 id="2-用于映射的生成器函数"><a href="#2-用于映射的生成器函数" class="headerlink" title="2. 用于映射的生成器函数"></a>2. 用于映射的生成器函数</h4><table>
<thead>
<tr>
<th>模块</th>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>itertools</td>
<td>accumulate(it, [func])</td>
<td>产出累积的总和；如果提供了 func，那么把前两个 元素传给它，然后把计算结果和下一个元素传给 它，以此类推，最后产出结果</td>
</tr>
<tr>
<td></td>
<td>enumerate(iterable, start=0)</td>
<td>产出由两个元素组成的元组，结构是 (index, item)，其中 index 从 start 开始计数，item 则从 iterable 中获取</td>
</tr>
<tr>
<td></td>
<td>map(func, it1, [it2, …, itN])</td>
<td>把 it 中的各个元素传给func，产出结果；如果传入 N 个可迭代的对象，那么 func 必须能接受 N 个参 数，而且要并行处理各个可迭代的对象</td>
</tr>
<tr>
<td>itertools</td>
<td>starmap(func, it)</td>
<td>把 it 中的各个元素传给 func，产出结果；输入的 可迭代对象应该产出可迭代的元素 iit，然后以 func(*iit) 这种形式调用 func</td>
</tr>
</tbody></table>
<h4 id="3-合并多个可迭代对象的生成器函数"><a href="#3-合并多个可迭代对象的生成器函数" class="headerlink" title="3. 合并多个可迭代对象的生成器函数"></a>3. 合并多个可迭代对象的生成器函数</h4><table>
<thead>
<tr>
<th>模块</th>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>itertools</td>
<td>chain(it1, …, itN)</td>
<td>先产出 it1 中的所有元素，然后产出 it2 中的 所有元素，以此类推，无缝连接在一起</td>
</tr>
<tr>
<td>itertools</td>
<td>chain.from_iterable(it)</td>
<td>产出 it 生成的各个可迭代对象中的元素，一个 接一个，无缝连接在一起；it 应该产出可迭代 的元素，例如可迭代的对象列表</td>
</tr>
<tr>
<td>itertools</td>
<td>product(it1, …, itN, repeat=1)</td>
<td>计算笛卡儿积：从输入的各个可迭代对象中获 取元素，合并成由 N 个元素组成的元组，与嵌 套的 for 循环效果一样；repeat 指明重复处理 多少次输入的可迭代对象</td>
</tr>
<tr>
<td></td>
<td>zip(it1, …, itN)</td>
<td>并行从输入的各个可迭代对象中获取元素，产 出由 N 个元素组成的元组，只要有一个可迭代 的对象到头了，就默默地停止</td>
</tr>
<tr>
<td>itertools</td>
<td>zip_longest(it1, …, itN, fillvalue=None)</td>
<td>并行从输入的各个可迭代对象中获取元素，产 出由 N 个元素组成的元组，等到最长的可迭代 对象到头后才停止，空缺的值使用 fillvalue 填充</td>
</tr>
</tbody></table>
<h4 id="4-把输入的各个元素扩展成多个输出元素的生成器对象"><a href="#4-把输入的各个元素扩展成多个输出元素的生成器对象" class="headerlink" title="4. 把输入的各个元素扩展成多个输出元素的生成器对象"></a>4. 把输入的各个元素扩展成多个输出元素的生成器对象</h4><table>
<thead>
<tr>
<th>模块</th>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>itertools</td>
<td>combinations(it, out_len)</td>
<td>把 it 产出的 out_len 个元素组合在 一起，然后产出</td>
</tr>
<tr>
<td>itertools</td>
<td>combinations_with_replacement(it, out_len)</td>
<td>把 it 产出的 out_len 个元素组合在 一起，然后产出，包含相同元素的 组合</td>
</tr>
<tr>
<td>itertools</td>
<td>count(start=0, step=1)</td>
<td>从 start 开始不断产出数字，按 step 指定的步幅增加</td>
</tr>
<tr>
<td>itertools</td>
<td>cycle(it)</td>
<td>从 it 中产出各个元素，存储各个元 素的副本，然后按顺序重复不断地 产出各个元素</td>
</tr>
<tr>
<td>itertools</td>
<td>permutations(it, out_len=None)</td>
<td>把 out_len 个 it 产出的元素排列在 一起，然后产出这些排列；out_len的默认值等于 len(list(it))</td>
</tr>
<tr>
<td>itertools</td>
<td>repeat(item, [times])</td>
<td>重复不断地产出指定的元素，除非 提供 times，指定次数</td>
</tr>
</tbody></table>
<h4 id="5-用于重新排列元素的生成器函数"><a href="#5-用于重新排列元素的生成器函数" class="headerlink" title="5. 用于重新排列元素的生成器函数"></a>5. 用于重新排列元素的生成器函数</h4><table>
<thead>
<tr>
<th>模块</th>
<th>函数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>itertools</td>
<td>groupby(it,key=None)</td>
<td>产出由两个元素组成的元素，形式为 (key, group)，其中 key 是分组标准，group 是生成器， 用于产出分组里的元素</td>
</tr>
<tr>
<td></td>
<td>reversed(seq)</td>
<td>从后向前，倒序产出 seq 中的元素；seq 必须是序 列，或者是实现了 <strong>reversed</strong> 特殊方法的对象</td>
</tr>
<tr>
<td>itertools</td>
<td>tee(it, n=2)</td>
<td>产出一个由 n 个生成器组成的元组，每个生成器 用于单独产出输入的可迭代对象中的元素</td>
</tr>
</tbody></table>
<h3 id="简单小结"><a href="#简单小结" class="headerlink" title="简单小结"></a>简单小结</h3><ul>
<li><strong>iterable对象</strong>：可迭代对象，实现了返回迭代器的<code>__iter__()</code>方法或者<code>__gititem__()</code>方法且其参数是从0开始的索引。包含容器、迭代器等。</li>
<li><strong>container对象</strong>：容器对象，所有容器中的元素被存储在内存中。像list、tuple、str、dict等对象。</li>
<li><strong>iterator对象</strong>：迭代器对象，不同于container的数据存储形式，iterator只存储算法的内存地址，iterator对象与iterable对象不同之处在于，iterator<strong>同时具有<code>__iter__()</code>和<code>__next__()</code>方法。</strong>尽管像列表、元祖这样的对象不具有<code>__next__()</code>方法<strong>，但是可以通过<code>iter()</code>方法或者for语句为它们返回一个迭代器对象。</strong></li>
<li><strong>generator对象</strong>：生成器对象是特殊的迭代器，具有迭代器一切的特点。创建generator对象一般有两种方法，一种是生成器表达式，形式上与列表、集合解析式很像，实质却完全不同；另一种创建方式<code>yield</code>生成器函数。</li>
</ul>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io" rel="external nofollow noreferrer">张亚飞</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io/python/base/di-28-pian-die-dai-qi-he-sheng-cheng-qi/">https://zhangyafeii.gitee.io/python/base/di-28-pian-die-dai-qi-he-sheng-cheng-qi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                                    <span class="chip bg-color">Python之路</span>
                                </a>
                            
                                <a href="/tags/%E5%8F%AF%E8%BF%AD%E4%BB%A3%E5%AF%B9%E8%B1%A1/">
                                    <span class="chip bg-color">可迭代对象</span>
                                </a>
                            
                                <a href="/tags/%E8%BF%AD%E4%BB%A3%E5%99%A8/">
                                    <span class="chip bg-color">迭代器</span>
                                </a>
                            
                                <a href="/tags/%E7%94%9F%E6%88%90%E5%99%A8/">
                                    <span class="chip bg-color">生成器</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b9bf0e29501275f4f23c',
        clientSecret: '1c56bc88fdb7b23ee3712916a38e5e8d1311823a',
        repo: 'github.io',
        owner: 'zhangyafeii',
        admin: "zhangyafeii",
        id: '2020-12-27T10-00-01',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/python/base/di-27-pian-zhuang-shi-qi/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/27.jpg" class="responsive-img" alt="第27篇：装饰器">
                        
                        <span class="card-title">第27篇：装饰器</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            学习目标：掌握装饰器相关知识点
今天来学函数的第二个高阶应用，装饰器，装饰器属于Python的核心特色，学了这两个高阶功能，我们就可以做更多事情了。
装饰器是Python中用一个函数装饰另外一个函数或类并可以在不改变函数或方法的调用方式的情
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-12-27
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Python/" class="post-category">
                                    Python
                                </a>
                            
                            <a href="/categories/Python/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Python之路</span>
                    </a>
                    
                    <a href="/tags/%E8%A3%85%E9%A5%B0%E5%99%A8/">
                        <span class="chip bg-color">装饰器</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/go/base/di-6-pian-qie-pian/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/6.jpg" class="responsive-img" alt="第6篇：引用数据类型之切片">
                        
                        <span class="card-title">第6篇：引用数据类型之切片</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Slice（切片）代表变长的序列，可以理解为动态数组，序列中每个元素都有相同的类型。一个slice类型一般写作[]T，其中T代表slice中元素的类型；slice的语法和数组很像，只是没有固定长度而已。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-12-27
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E5%BC%95%E7%94%A8%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/">
                        <span class="chip bg-color">引用数据类型</span>
                    </a>
                    
                    <a href="/tags/%E5%88%87%E7%89%87/">
                        <span class="chip bg-color">切片</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 飞凡空间<br />'
            + '文章作者: 张亚飞<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">344.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "12";
                    var startDate = "18";
                    var startHour = "12";
                    var startMinute = "12";
                    var startSecond = "12";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-google-plus"></i>
    </a>



    <a href="mailto:zhangyafeii@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1271570224" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1271570224" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/js/cursor.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
